package com.xywh.dakaqiandao.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.ButtonBarLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.xywh.dakaqiandao.R;
import com.xywh.dakaqiandao.di.component.DaggerMySalaryDetailComponent;
import com.xywh.dakaqiandao.di.module.MySalaryDetailModule;
import com.xywh.dakaqiandao.mvp.contract.MySalaryDetailContract;
import com.xywh.dakaqiandao.mvp.presenter.MySalaryDetailPresenter;
import com.xywh.dakaqiandao.mvp.ui.entity.MySalaryDetail;
import com.xywh.dakaqiandao.mvp.ui.util.GlideUtil;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;

import static com.jess.arms.base.BaseConstants.BASE_URL;
import static com.jess.arms.base.BaseConstants.NAME_SPACE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_MY_SALARY_DETAIL)
public class MySalaryDetailActivity extends BaseActivity<MySalaryDetailPresenter> implements MySalaryDetailContract.View {

    @BindView(R.id.tv_ji_ben_gong_zi)
    TextView tvJiBenGongZi;
    @BindView(R.id.tv_gang_wei_gong_zi)
    TextView tvGangWeiGongZi;
    @BindView(R.id.tv_ji_xiao_gong_zi)
    TextView tvJiXiaoGongZi;
    @BindView(R.id.tv_jiang_jin)
    TextView tvJiangJin;
    @BindView(R.id.tv_jin_tie_can_bu)
    TextView tvJinTieCanBu;
    @BindView(R.id.tv_jin_tie_jiao_tong)
    TextView tvJinTieJiaoTong;
    @BindView(R.id.tv_jia_ban_tian_shu)
    TextView tvJiaBanTianShu;
    @BindView(R.id.tv_jia_ban_jin_e)
    TextView tvJiaBanJinE;
    @BindView(R.id.tv_ge_ren_ying_fa_he_ji)
    TextView tvGeRenYingFaHeJi;
    @BindView(R.id.tv_qing_jia_tian_shu)
    TextView tvQingJiaTianShu;
    @BindView(R.id.tv_qing_jia_jin_e)
    TextView tvQingJiaJinE;
    @BindView(R.id.tv_qi_ta_kou_kuan)
    TextView tvQiTaKouKuan;
    @BindView(R.id.tv_fu_li_dai_jiao_yang_lao)
    TextView tvFuLiDaiJiaoYangLao;
    @BindView(R.id.tv_fu_li_dai_jiao_yi_liao)
    TextView tvFuLiDaiJiaoYiLiao;
    @BindView(R.id.tv_fu_li_dai_jiao_shi_ye)
    TextView tvFuLiDaiJiaoShiYe;
    @BindView(R.id.tv_fu_li_dai_jiao_zhu_fang_gong_ji_jin)
    TextView tvFuLiDaiJiaoZhuFangGongJiJin;
    @BindView(R.id.tv_ge_ren_suo_de_shui)
    TextView tvGeRenSuoDeShui;
    @BindView(R.id.tv_ge_ren_ying_kou_he_ji)
    TextView tvGeRenYingKouHeJi;
    @BindView(R.id.tv_shi_fa_gong_zi)
    TextView tvShiFaGongZi;
    @BindView(R.id.img_signature)
    ImageView imgSignature;
    @BindView(R.id.btn_ok)
    Button btnOk;
    @BindView(R.id.nsv)
    NestedScrollView nsv;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.buttonBarLayout)
    ButtonBarLayout buttonBarLayout;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_jin_tie_gao_wen_bu_tie)
    TextView tvJinTieGaoWenBuTie;
    @BindView(R.id.ll_gao_wen_bu_tie)
    LinearLayout llGaoWenBuTie;
    private String mYearDay;
    private boolean isSignature = false;
    private String mSalaryId;
    private Bitmap mSignatureBitmap;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMySalaryDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .mySalaryDetailModule(new MySalaryDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_my_salary_detail; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_my_salary_detail));
        //getMySalaryDetailData();
        mYearDay = getIntent().getExtras().getString("yearDay");
        getSalary();
        nsv.post(new Runnable() {
            @Override
            public void run() {
                nsv.fullScroll(View.FOCUS_DOWN);//滚到底部
//                nestedScrollView.fullScroll(ScrollView.FOCUS_UP);//滚到顶部
            }
        });
    }

    private void getSalary() {

        showLoading();

        String methodName = "getSalary";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("identityCardNo", mSharedPreferencesHelper.getString(BaseConstants.USERNAME));
        params.put("yearDay", mYearDay);


        /**
         * 请求
         */
        soapUtil.callEntry(BASE_URL, NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                try {
                    String result = object.getProperty("getSalaryResult").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("-1")) {
                        MySalaryDetail mySalaryDetail = new Gson().fromJson(result, MySalaryDetail.class);
                        tvJiBenGongZi.setText(mySalaryDetail.getJiben());
                        tvGangWeiGongZi.setText(mySalaryDetail.getGangwei());
                        tvJiXiaoGongZi.setText(mySalaryDetail.getJixiao());
                        tvJiangJin.setText(mySalaryDetail.getJiangjin());
                        tvJinTieCanBu.setText(mySalaryDetail.getCanbu());
                        if (!TextUtils.isEmpty(mySalaryDetail.getGaowenbutie()) && (!mySalaryDetail.getGaowenbutie().equals("0"))) {
                            tvJinTieGaoWenBuTie.setText(mySalaryDetail.getGaowenbutie());
                            llGaoWenBuTie.setVisibility(View.VISIBLE);
                        } else {
                            llGaoWenBuTie.setVisibility(View.GONE);
                        }
//                        tvJinTieJiaoTong.setText(mySalaryDetail.getCanbu());
                        tvJinTieJiaoTong.setText(mySalaryDetail.getJiaotong());
                        tvJiaBanTianShu.setText(mySalaryDetail.getJiabandays());
                        tvJiaBanJinE.setText(mySalaryDetail.getJiabanjine());
                        tvGeRenYingFaHeJi.setText(mySalaryDetail.getYingfaheji());
                        tvQingJiaTianShu.setText(mySalaryDetail.getQingjiadays());
                        tvQingJiaJinE.setText(mySalaryDetail.getQingjiajine());
                        tvQiTaKouKuan.setText(mySalaryDetail.getKoufa());
                        tvFuLiDaiJiaoYangLao.setText(mySalaryDetail.getYanglao());
                        tvFuLiDaiJiaoYiLiao.setText(mySalaryDetail.getYiliao());
                        tvFuLiDaiJiaoShiYe.setText(mySalaryDetail.getShiye());
                        tvFuLiDaiJiaoZhuFangGongJiJin.setText(mySalaryDetail.getGongjijin());
                        tvGeRenSuoDeShui.setText(mySalaryDetail.getGeshui());
                        tvGeRenYingKouHeJi.setText(mySalaryDetail.getYingkouheji());
                        tvShiFaGongZi.setText(mySalaryDetail.getShifagongzi());

                        mSalaryId = mySalaryDetail.getSalaryId();
                        if (mySalaryDetail.getStatus().equals("0")) {
                            setBtnBlue();
                        } else if (mySalaryDetail.getStatus().equals("1")) {
                            if (!TextUtils.isEmpty(mySalaryDetail.getSignImg())) {
                                GlideUtil.loadImage(getContext(), mySalaryDetail.getSignImg(), imgSignature, R.drawable.icon_signature);
                            }
                            setBtnGray();
                        }


                    } else {


                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    private void setBtnBlue() {
        imgSignature.setEnabled(true);
        btnOk.setEnabled(true);
        btnOk.setBackground(getResources().getDrawable(R.drawable.public_shape_blue_bg_corner_5dp));
        btnOk.setText("确认工资");
    }

    private void setBtnGray() {
        imgSignature.setEnabled(false);
        btnOk.setEnabled(false);
        btnOk.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
        btnOk.setText("工资已确认");
    }

    @Override
    public void getMySalaryDetailDataSuccess(MySalaryDetail entityData) {


    }

    private void getMySalaryDetailData() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getMySalaryDetailData(map);
    }

    @OnClick(R.id.btn_ok)
    public void onViewClicked() {
//        if (isSignature) {
        showConfirmMessageDialog();
//        } else {
//            showMessage("您还没有签名，请先签名！！！");
//            Utils.navigation(getContext(), RouterHub.ACTIVITY_SIGNATURE_PAD);
//        }
    }

    private void showConfirmMessageDialog() {
        new QMUIDialog.CheckBoxMessageDialogBuilder(this)
                .setTitle("确认工资?")
                .setMessage("本人对当月薪资以及福利内容已知晓并确认，同时本人承诺遵守公司保密制度对自己的薪资福利绝对保密。")
                .setChecked(true)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
//                        startActivityForResult(new Intent(getContext(), SignaturePadActivity.class), 105);

                        Utils.navigation(getContext(), RouterHub.ACTIVITY_SIGNATURE_PAD);
//                        if (!TextUtils.isEmpty(mSalaryId) && mSignatureBitmap != null) {
//                            setBtnGray();
//                            updateSalaryStatus(mSalaryId, ArmsUtils.bitmapToBase64String(mSignatureBitmap));
//                        }
                    }
                })
                .create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();
    }

    @OnClick(R.id.img_signature)
    public void signature() {
        Utils.navigation(getContext(), RouterHub.ACTIVITY_SIGNATURE_PAD);
    }

    @Subscriber(tag = "setSignaureImg", mode = ThreadMode.MAIN)
    public void setSignaureImg(Bitmap bitmap) {
        try {
            mSignatureBitmap = bitmap;
            isSignature = true;
            imgSignature.setImageBitmap(bitmap);

            if (!TextUtils.isEmpty(mSalaryId) && mSignatureBitmap != null) {
                setBtnGray();
                updateSalaryStatus(mSalaryId, ArmsUtils.bitmapToBase64String(mSignatureBitmap));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateSalaryStatus(String salaryId, String image) {

        showLoading();

        String methodName = "updateSalaryStatus";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("salaryId", salaryId);
        params.put("identityCardNo", mSharedPreferencesHelper.getString(BaseConstants.USERNAME));
        params.put("yearDay", mYearDay);
        params.put("image", image);


        /**
         * 请求
         */
        soapUtil.callEntry(BASE_URL, NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                try {
                    String result = object.getProperty("updateSalaryStatusResult").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("-1")) {

                        if (result.equals("1")) {
                            showMessage("确认工资成功");
                            EventBus.getDefault().post("", "refreshSalaryAll");
                        } else if (result.equals("-2")) {
                            showMessage("签名上传失败");
                            setBtnBlue();
                        }
                    } else {
                        showMessage("确认工资失败");
                        setBtnBlue();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    setBtnBlue();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
                setBtnBlue();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
                setBtnBlue();
            }
        }, getAapiUserName(), getApiPwd());


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
